package com.vitas.coin.ui.adapter;

import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.vitas.coin.R;
import com.vitas.coin.data.bean.ChildrenVoiceBean;
import com.vitas.coin.databinding.ListItemBinding;
import com.vitas.coin.ui.dialog.ListDlg;

import java.util.List;

public class ListAdapter extends RecyclerView.Adapter {
    ListDlg dlg;
    LayoutInflater inflater;
    List<ChildrenVoiceBean> list;
    int now;

    public ListAdapter(ListDlg dlg, int now, List list) {
        inflater = LayoutInflater.from(dlg.getActivity());
        this.dlg = dlg;
        this.list = list;
        this.now = now;
    }

    public void updateNow(int i) {
        if (now == i) {
            return;
        }
        int tmp = now;
        now = i;
        notifyItemChanged(tmp);
        notifyItemChanged(now);
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ListItemBinding binding = ListItemBinding.inflate(inflater, parent, false);
        return new Holder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof Holder) {
            ((Holder) holder).bind(position);
        }
    }

    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }

    class Holder extends RecyclerView.ViewHolder {
        ListItemBinding binding;

        Holder(ListItemBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }

        void bind(int p) {
            binding.title.setText(list.get(p).getName());
            if (now == p) {
                binding.getRoot().setBackgroundResource(R.drawable.light_gray_bg);
            } else {
                binding.getRoot().setBackground(null);
            }
            binding.delete.setOnClickListener(v -> {
                int tmp = getAdapterPosition();
                if (now == tmp) {
                    now = -1;
                }
                dlg.remove(tmp);
            });
            binding.getRoot().setOnClickListener(v -> {
                int tmp = getAdapterPosition();
                if (tmp == now) {
                    return;
                }
                dlg.play(tmp);
            });
        }
    }
}
